package com.ziyun.erp.modules.order.service.impl;

import com.service.model.quote.constant.AttributeValueType;
import com.service.quote.module.quote.model.CutModel;
import com.ziyun.erp.common.e.goods.GoodsTypeEnum;
import com.ziyun.erp.common.e.order.PayStatusEnum;
import com.ziyun.erp.common.e.order.PrintModeType;
import com.ziyun.erp.common.e.order.PromotionTypeEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.modules.order.dao.*;
import com.ziyun.erp.modules.order.dto.OrderItemAuditDto;
import com.ziyun.erp.modules.order.entity.*;
import com.ziyun.erp.modules.order.service.*;
import com.ziyun.erp.modules.order.vo.*;
import com.ziyun.erp.modules.production.operate.ErpOrderStateContext;
import com.ziyun.erp.modules.production.operate.WaitAuditState;
import com.ziyun.erp.modules.production.operate.entity.AuditStateEntity;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;

@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Autowired
    private OrderRemarksService orderRemarksService;
    @Autowired
    private DesignInfoService designInfoService;
    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<OrderItemEntity> page = this.selectPage(
                new Query<OrderItemEntity>(params).getPage(),
                new EntityWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<OrderItemEntity> selectByOrderId(Long orderId) {
        List<OrderItemEntity> result = baseMapper.selectByOrderId(orderId);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R orderItemAudit(OrderItemAuditDto orderItemAuditDto, Long userId, String username) {
        ValidatorUtils.validateEntity(orderItemAuditDto);
        String orderId = orderItemAuditDto.getOrderId();
        OrderInfoEntity orderInfoEntity = orderInfoService.selectById(orderId);
        String promotionType = orderInfoEntity.getPromotionType();
        String payStatus = orderInfoEntity.getPayStatus();
        if (StringUtils.equals(promotionType, PromotionTypeEnum.PROCUREMENT.toCode())){
            if (!StringUtils.equals(payStatus, PayStatusEnum.PAPER_WAIT_AUDIT_6.toCode())){
                return R.error("订单审核状态异常");
            }
        }else {
            if (!StringUtils.equals(payStatus, PayStatusEnum.ALREADY_PAY_1.toCode())){
                return R.error("未支付订单无法审核");
            }
        }

        try {
            ErpOrderStateContext erpOrderStateContext = new ErpOrderStateContext(new WaitAuditState(),
                    new AuditStateEntity(orderItemAuditDto.getOrderId(), orderItemAuditDto.getItemId(), userId));
            R audit = erpOrderStateContext.audit();
            int code = (int) audit.get("code");
            if (code == 500){
                return audit;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RRException("系统异常，请联系后台管理员！");
        }

        // 添加备注信息
        String remark = orderItemAuditDto.getRemark();
        if (StringUtils.isNotBlank(remark)){
            OrderRemarksEntity orderRemarksEntity = new OrderRemarksEntity();
            orderRemarksEntity.setOrOrderId(Long.valueOf(orderItemAuditDto.getOrderId()));
            orderRemarksEntity.setOrItemId(orderItemAuditDto.getItemId());
            orderRemarksEntity.setOrCreateTime(new Date());
            orderRemarksEntity.setOrCreateName(username);
            orderRemarksEntity.setOrRemarks(remark);
            orderRemarksService.insert(orderRemarksEntity);
        }
        // 设计商品修改设计师
        if (StringUtils.equals(GoodsTypeEnum.DESIGN.toCode(), orderItemAuditDto.getGoodsType())){
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("designUserId",orderItemAuditDto.getDesigener());
            updateMap.put("orderId",orderItemAuditDto.getOrderId());
            updateMap.put("orderItemId",orderItemAuditDto.getItemId());
            updateMap.put("designApprovaTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            designInfoService.updateInfoByMap(updateMap);
        }

        erpOrderLogService.insertOrderItemLog(orderItemAuditDto.getOrderId(), Long.valueOf(orderItemAuditDto.getItemId()), "订单审核");

        return R.ok();
    }

    @Override
    public OrderItemVo selectOrderItemVoById(Integer itemId) {
        return this.baseMapper.selectOrderItemVoById(itemId);
    }

    @Override
    public boolean updateByMap(Map<String, Object> updateMap, Integer itemId) {
        int count = this.baseMapper.updateByMap(updateMap, itemId);
        if (count == 0){
            return false;
        }
        return true;
    }

    @Override
    public List<OrderItemVo> selectOrderItemVosById(Long orderId) {
        return this.baseMapper.selectOrderItemVosByOrderId(orderId);
    }

    @Override
    public OrderItemQuoteVo resolveQuoteItem(Integer itemId) {
        return getQuoteGoodsView(this.selectById(itemId));
    }

    public OrderItemQuoteVo getQuoteGoodsView(OrderItemEntity orderItem) {
        OrderItemQuoteVo orderItemQuote = new OrderItemQuoteVo();
        try {
            BigDecimal amount = orderItem.getAmount();//总价
            String addon = orderItem.getAddon();//规格参数
            if (StringUtils.isNotBlank(addon)) {
                List<QuoteProductInfoParamVo> quoteProductInfoList = JsonUtils.string2Collection(addon, ArrayList.class, QuoteProductInfoParamVo.class);
                orderItemQuote.setQuoteProductInfoList(quoteProductInfoList);
            }
            BigDecimal costPrice = BigDecimal.ZERO;//成本价
            String calculationPriceProcess = orderItem.getCalculationPriceProcess();//报价计算过程
            if (StringUtils.isNotBlank(calculationPriceProcess)) {
                PaperInfoWrapper paperInfoWrapper = JsonUtils.getJsonToObject(calculationPriceProcess, PaperInfoWrapper.class);
                List<PaperInfoVO> paperInfoList = paperInfoWrapper.getPaperInfoVOs();
                BigDecimal totalCraftPrice = BigDecimal.ZERO;
                BigDecimal totalPrintPrice = BigDecimal.ZERO;
                Map<String, BigDecimal> attributeValueTypeMap = new HashMap<>();
                for (PaperInfoVO info : paperInfoList) {
                    PrintModeType printModeType = info.getPrintModeType();
                    if (printModeType != null){
                        info.setPrintModeTypeName(printModeType.getNameType());
                    }
                    CutModel cutModel = info.getCutModel();
                    if (cutModel != null){
                        costPrice = costPrice.add(BigDecimal.valueOf(cutModel.getCostPrice()));
                        totalCraftPrice = totalCraftPrice.add(BigDecimal.valueOf(cutModel.getCraftCostPrice()));
                        totalPrintPrice = totalPrintPrice.add(BigDecimal.valueOf(cutModel.getPrintCostPrice())).add(BigDecimal.valueOf(info.getPaperPrice()));
                        Map<AttributeValueType, Double> craftPriceMap = cutModel.getCraftPriceMap();
                        if (craftPriceMap != null && craftPriceMap.size() > 0) {
                            for (Map.Entry<AttributeValueType, Double> entry : craftPriceMap.entrySet()) {
                                AttributeValueType key = entry.getKey();
                                Double value = entry.getValue();
                                if (attributeValueTypeMap.containsKey(key.getName())) {
                                    BigDecimal bd = attributeValueTypeMap.get(key.getName());
                                    bd = bd.add(BigDecimal.valueOf(value));
                                    attributeValueTypeMap.put(key.getName(), bd);
                                } else {
                                    attributeValueTypeMap.put(key.getName(), BigDecimal.valueOf(value));
                                }
                            }
                        }
                    }
                }
                if (attributeValueTypeMap.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (Map.Entry<String, BigDecimal> entry : attributeValueTypeMap.entrySet()) {
                        sb.append(entry.getKey()).append("（" + entry.getValue() + "）&nbsp;&nbsp;");
                    }
                    orderItemQuote.setAttributeValueTypeMap(sb.toString());
                }
                orderItemQuote.setPrintType(paperInfoWrapper.getPrintType());
                orderItemQuote.setPaperInfoList(paperInfoList);
                orderItemQuote.setTotalCraftPrice(totalCraftPrice);
                orderItemQuote.setTotalPrintPrice(totalPrintPrice);
            }
            orderItemQuote.setTotalTotalPrice(amount);
            orderItemQuote.setSubtract(amount.subtract(costPrice));//利润
        }catch (Exception e){
            e.printStackTrace();
        }
        return orderItemQuote;
    }

}
